<template>
	<view class="">
		<!-- <template> -->
			<!-- 订单待支付金额 -->
			<view class="text-center p-y-25 text-13">
				<view class="flex align-center justify-center m-b-6">
					<text class="m-r-5 color-33">支付剩余时间</text>
					<tui-countdown :time="expiredTime" @end="getPayTypeList" />
				</view>
				<view class="flex align-center justify-center m-b-6">
					<basic-price :decimal="36" :number="36" :price="payInfo?.payAmount || 0" :unit="20" :weight="500" color="#000" />
				</view>
				<view class="flex align-center justify-center color-99">
					<text class="m-r-6">订单编号：</text>
					<text>{{ payInfo?.payCode || '111' }}</text>
				</view>
			</view>
			<!-- 支付方式 2-->
		<!-- 	<view class="m-x-10">
				<view class="pay-Box border-radius-8 bg-white p-x-14">
					<view v-for="(item, index) in payTypeObj.normal" :key="item.payWay"  @click="changePayType(index, 'normal')" class="flex justify-between align-center">
						<view :class="{'pay-Box-border': index !== payTypeObj.normal.length - 1}" class="flex-1 m-l-10 p-y-16 p-r-2 flex align-center justify-between">
							<view style="display: flex;justify-content: center;align-items: center;">
								<image style="width: 30px;height: 30px;" :src="item.url" mode=""></image>
								<view class="color-00 text-14" style="margin-left: 20rpx;">{{ item.name }}</view>
							</view>
							<text :class="[item.isSelect ? 'iconfont icon-chenggong1 select newWidth isSelect' : 'notSelect newWidth']" class="text-24 checkBox"></text>
						</view>
					</view>
				</view>
			</view> -->
		<!-- </template> -->

		<!-- 确认交易按钮 -->
		<!-- <basic-tabbar background="#fff"> -->
		
		<!-- #ifdef APP -->
		<!-- 微信支付app端 -->
		<view class="flex-1 flex align-center justify-center p-x-12" style="margin-top: 20rpx;">
			<tui-button :disabled="payLoading" :loading="payLoading" block class="flex-1 common-tab-btn text-14"
				shape="circle" type="green" @click="WeiXinPay_app">
				微信支付
			</tui-button>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<!-- 微信支付小程序端 -->
		<view class="flex-1 flex align-center justify-center p-x-12" style="margin-top: 20rpx;">
			<tui-button :disabled="payLoading" :loading="payLoading" block class="flex-1 common-tab-btn text-14"
				shape="circle" type="primary" @click="platformPay">
				确认交易
			</tui-button>
		</view>
		<!-- #endif -->
		
		<!-- </basic-tabbar> -->
	</view>
</template>

<script setup name="cashier">
	import {
		reactive,
		ref,
		watch
	} from 'vue'
	import {
		AppPay
	} from '@/util/platform/app/pay'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		debounce
	} from 'lodash'
	import {
		notifyAPI,
		countdown
	} from '@/api/index'
	
	import {
		ifFirstOrder
	} from '@/api/user'
	
	import uniApi from '@/util/uniApi/index'
	import {
		getQueryValueByKey
	} from '@/util/lib/common'

	import $store from '@/store/index'
	// import payPopUp from '@/pages-subpackage/common/components/diyPayPopup'
	// import byCodePopUp from '../../components/codePopup'

	// 跳转过来支付的参数信息
	const payParams = ref({
		payCode: ''
	})

	// 页面支付信息
	const payInfo = ref(null)
	const expiredTime = ref(0)

	// 支付方式['新华阅读卡支付', '微信支付等']
	const payTypeObj = reactive({
		normal: [
			{name:'微信支付',isSelect:false,url:'/static/wx.png'},
			{name:'支付宝支付',isSelect:false,url:'/static/zfb.png'}
		]
	})
	// 阅读卡支付弹窗及必要卡信息
	const payPopup = ref(false)
	const payCardInfo = reactive({
		cardNo: '',
		cardPwd: ''
	})
	// 支付loading
	const payLoading = ref(false)

	const showByPayCode = ref(false)
	const byCode = ref('')

	// watch((data)=>{
	// 	expiredTime:(data)=>{
	// 		console.log()
	// 	}
	// }),
	onLoad(() => {
		// 获取支付单参数来源
		getPayParams()
		// 查询支付单详情&支付方式
		getPayTypeList()
		// 新建订单触发订单页 getList
		if (payParams.value.jumpType === 0) {
			uni.$emit('orderListRefresh')
			uni.$emit('coffeeOrderListRefresh')
			uni.$emit('activityOrderListRefresh')
			uni.$emit('ticketOrderListRefresh')
			uni.$emit('spaceOrderListRefresh')
			uni.$emit('selfOrderListRefresh')
		}
		
	})
	
	
	function ifFirstOrders(){
		const pageUrl = payParams.value.backUrlKey
		console.log(pageUrl)
		uni.switchTab({
			url: pageUrl
		})
		// const pageUrl = payParams.value.backUrlKey
		// ifFirstOrder({openId:uni.getStorageSync('user').userId}, 'get')
		// .then((res) => {
		// 	if(res){
		// 		uni.redirectTo({
		// 			url: '/pages/myPage/lottery'
		// 		})
		// 	}else{
		// 		uni.switchTab({
		// 			url: pageUrl
		// 		})
		// 	}
		// })
	}


	// 获取支付参数
	function getPayParams() {
		const orderPayParams = $store('app').payParams
		if (!orderPayParams) return
		payParams.value = orderPayParams
	}

	// 平台级支付
	const platformPay = debounce(async () => {
		
		countdown({
				orderId: payInfo.value.payCode
			}, 'get')
			.then((res) => {
				if (res.code == 200) {
					console.log(res)
					if(res.msg <= 0){
						uniApi.toast({
							title: '订单已超时请重新下单',
							icon: 'none'
						})
						return false;
					}else{
						const pageUrl = payParams.value.backUrlKey
						// 拉起支付
						AppPay({
							payType: 'WX_LITE',
							payorderId: payParams.value.payCode
						}).then((res) => {
							let data = {
								id: payParams.value.payCode
							}
							notifyAPI(data, 'get')
								.then((res) => {
									console.log(res, '支付成功');
									ifFirstOrders();
								})
						
							// 支付成功
						
						}).catch((errMsg) => {
							console.log(errMsg, '111111111111111');
							uni.showLoading({
								title: '请稍后',
							});
							uniApi.toast({
								title: '已取消支付',
								icon: 'none'
							})
							// 取消支付将返回列表
							uni.setStorageSync('activeId', 0)
							$store('app').clearPayCashierParams()
							uni.switchTab({
								url: pageUrl
							})
						})
					}
				}else{
					uniApi.toast({
						title: '订单已超时请重新下单',
						icon: 'none'
					})
				}
			}).fail((err)=>{
				console.log(err)
			})
			
		console.log(expiredTime)
		
		return false;
		
	}, 500)
	// app内微信支付
	function WeiXinPay_app(){
		uni.getProvider({
			service: 'oauth',
			success: function (res) {
				console.log(res.provider); // 输出支持的服务供应商
				if(res.provider['weixin'] != -1){
					uni.requestPayment({
					    "provider": "wxpay",
					    "orderInfo": {
					        "appid": "wx499********7c70e",  // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
					        "noncestr": "c5sEwbaNPiXAF3iv", // 随机字符串
					        "package": "Sign=WXPay",        // 固定值
					        "partnerid": "148*****52",      // 微信支付商户号
					        "prepayid": "wx202254********************fbe90000", // 统一下单订单号
					        "timestamp": 1597935292,        // 时间戳（单位：秒）
					        "sign": "A842B45937F6EFF60DEC7A2EAA52D5A0" // 签名，这里用的 MD5/RSA 签名
					    },
					    success(res) {},
					    fail(e) {}
					})
				}
			}
		})
	}



	// 可公用的初始支付参数
	function getPayInitialValue() {
		const params = {
			payCode: payParams.value.payCode,
			payWay: ''
		}
		params.payWay = payWayInfo.payWay
		params.payChannel = payWayInfo.channel

		if (payWayInfo?.cardInfo) {
			params.cardNo = payWayInfo.cardInfo.cardNo
		}

		return params
	}
	// 查询支付方式
	async function getPayTypeList() {
		let data = {
			payAmount: payParams.value.payAmount,
			payCode: payParams.value.payCode
		}
		payInfo.value = data
		countdown({
				orderId: payInfo.value.payCode
			}, 'get')
			.then((res) => {
				if (res.code == 200) {
					expiredTime.value = res.msg
					if(res.msg == "0"){
						uni.switchTab({
							url: "/pages/orderList/orderList"
						})
					}
				}
			})
	}

	// 切换支付方式
	function changePayType(index, type) {
		const ApiFunc = (selectList, otherList) => {
			console.log(payTypeObj[otherList])
			payTypeObj[selectList].forEach((item, i) => {
				item.isSelect = index === i
				if (item.cards) {
					item.cards = item.cards.map(v => {
						v.isSelect = false
						return v
					})
				}
			})
			payTypeObj[otherList].forEach(item => {
				item.isSelect = index === i
				// if (item.cards) {
				// 	item.cards = item.cards.map(v => {
				// 		v.isSelect = false
				// 		return v
				// 	})
				// }
			})
			console.log(payTypeObj)
			payCardInfo.cardNo = ''
			payCardInfo.cardPwd = ''
		}
		const otherType = 'normal'
		ApiFunc(type, otherType)
	}

	// 退出支付页面
	function cancelPayBack() {
		uniApi.modal({
			content: '确认离开收银台？',
			cancelText: '继续支付',
			confirmText: '确认离开',
			callback: () => {
				$store('app').clearPayCashierParams()
				switch (payParams.value.jumpType) {
					case 0:
						const pageUrl = payParams.value.backUrlKey
						uni.switchTab({
							url: pageUrl
						})
						// uniApi.redirect(`${pageUrl}?${payParams.value.orderParams}`)
						break
					case 1:
						uniApi.pageBack()
						break
				}
			}
		})
	}
	

	// 判断同一支付单是否有未支付的支付单
	async function testIsSamePayOrder() {
		const params = getPayInitialValue()
		let isSamePayOrder = ['WX_APP', 'WX_LITE'].includes(params.payWay)
		if (Boolean(Number(getQueryValueByKey('payTips', payParams.value.orderParams))) && !isSamePayOrder) {
			const {
				data
			} = await QueryPaymentCode({
				payCode: payParams.value.payCode,
				payWay: params.payWay
			})
			if (data) {
				uniApi.comfirmModal({
					content: data
				})
				payLoading.value = false
				return false
			}
		}
		return true
	}
</script>

<style lang="scss" scoped>
	.pay-Box {
		&-border {
			border-bottom: rpx2(0.5) solid #fafafa;
		}
	}

	.account-wrap-item {
		background-color: #F7F7F7;
		border: rpx2(1) solid #F7F7F7;

		&.isSelect {
			border: rpx2(1) solid #F2450B;
			background: #FFEDEC;
		}

		&.isUsed {
			opacity: .6;
			color: #ccc !important;
		}
	}
	
	.isSelect {
		// border: 1px solid #F2450B;
		background: #0055ff;
		border-radius: 50%;
		color: #ccc !important;
		:after{
			content: "";
			position: absolute;
			left: 18px;
			top: 22px;
			width: 15px;
			height: 7px;
			border: solid white;
			border-width: 0 0 3px 3px;
			transform: rotate(-45deg);
		}
	}
	
	.isSelect::after{
		content: "";
		width: 8px;
		height: 8px;
		display: block;
		background: #fff;
		transform: rotate(-45deg);
		border-radius: 50%;
	}
	
</style>